package com.dobby.logger.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * Created by liguoqing on 2016/3/7.
 */
public class CommonUtils {

    public static String getUUID() {
        String s = UUID.randomUUID().toString();
        return s.replace("-", "");
    }

    public static String DateToString(Date date, String formatStr) {
        SimpleDateFormat df = new SimpleDateFormat(formatStr);
        return df.format(date);
    }

    public static Date StringToDate(String date, String formatStr) {
        SimpleDateFormat df = new SimpleDateFormat(formatStr);

        try {
            return df.parse(date);
        } catch (ParseException var4) {
            var4.printStackTrace();
            return null;
        }
    }


    public static String DateAdd(String dateStr, int count, int field) {
        Calendar cd = Calendar.getInstance();
        if(StringUtils.isNotBlank(dateStr)) {
            cd.setTime(StringToDate(dateStr, "yyyy-MM-dd"));
            cd.add(field, count);
            dateStr = DateToString(cd.getTime(), "yyyy-MM-dd");
        }

        return dateStr;
    }

    public static Date DateAdd(Date date, int count, int field) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(field, count);
        return calendar.getTime();
    }

    public static Properties findProperties(String fileName){
        InputStream inputStream = CommonUtils.class.getClassLoader().getResourceAsStream(fileName);
        Properties p = new Properties();
        try{
            p.load(inputStream);
        } catch (IOException e1){
            e1.printStackTrace();
        }
        return p;
    }


    public static String getHostIp() {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            if(null != inetAddress) {
                return inetAddress.getHostAddress();
            } else {
                return "";
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "";
    }

}
